package com.future.baselib.pay;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.future.baselib.activity.BaseActivity;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 *  继承并重写 success和fail方法即可
 *  支付宝使用为上半部分，使用时只需修改APPID和私钥RSA2_PRIVATE，如需对提示信息修改，请修改OrderInfoUtil
 * Created by jniu on 2017/5/31.
 */

public abstract class PayActivity extends BaseActivity {

    /** 支付宝支付业务：入参app_id */
    public static final String ALI_APPID = "2018111262103915";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /** 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1 */
    public static final String RSA2_PRIVATE = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCBQPTetW/ecPB9CebhibOwBWMLk99B+PtQiNKUgjxnSNwkyJgi00LNHMywHre4SywG66xV9dVScy+QXkqkj47UCkPJrUSgAkWULLqz4DVTtMehCBoFVk6BKJGqkGNKYl8m76A7I4Bd+9pnxsmGaCZ+5YW8IUlqFdqCCSC5Tpx+R6RRXSbRCZ+iQslXPvwrSrWB/jK3/uByXtqdImSvdfvA6l0FzedX+2LooM/7ZJ3mMwcdAndxbPQYUdsfmsSkuEo+JEmjsW2PPhBbZrCb4zayq/iZpP5V1qa5Mog8uc/5IAVUCCQbYYJvxA0veyMV69zse2yDXDziiwt7mY/E7A69AgMBAAECggEAfSC6LeQu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1hGQBAvrVaYqx79BQHSFkklqJgruxbhTow1ASSFFwHw+eoaMLqdIfJIa8nbweWLXO1j9MPvWLYqQ3GknAROs9NsrqMmH3XJCPq2ktwUY1v8R0E7HTwGLB6nlJ/rZ";
    /**
     * 支付宝支付业务
     *
     */
    public void payAli(double price,String subject) {
        if (TextUtils.isEmpty(ALI_APPID) || (TextUtils.isEmpty(RSA2_PRIVATE))) {
            Toast.makeText(this, "需要配置APPID | RSA_PRIVATE", Toast.LENGTH_SHORT).show();
            return;
        }

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        String content = OrderInfoUtil.buildOrderContent(price, subject);
        Map<String, String> params = OrderInfoUtil.buildOrderParamMap(ALI_APPID,content, rsa2);
        String orderParam = OrderInfoUtil.buildOrderParam(params);

        String privateKey = RSA2_PRIVATE;
        String sign = OrderInfoUtil.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                paySuccess();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                payFail();
            }
        }
    };

    //TODO -----------------------------------------------------------------------------------------



    public void payWechat(double price,String subject){
        IWXAPI api = WXAPIFactory.createWXAPI(this,"WX_APP_ID",false);
        PayReq request = new PayReq();
        request.appId = "wxd930ea5d5a258f4f";
        request.partnerId = "1900000109";
        request.prepayId= "1101000000140415649af9fc314aa427";
        request.packageValue = "Sign=WXPay";
        request.nonceStr= "1101000000140429eb40476f8896f4c9";
        request.timeStamp= "1398746574";
        request.sign= "7FFECB600D7157C5AA49810D2D8F28BC2811827B";
        api.sendReq(request);
    }



    /**
     * 支付成功回调
     */
    public abstract void paySuccess();

    /**
     * 支付失败回调
     */
    public abstract void payFail();

}
